<template>

  <el-select :loading="loading" :modelValue="value" :placeholder="info.placeholder" :remote-method="remoteMethod" clearable
             filterable remote reserve-keyword
             @change="(value) => { $emit('update:value', value) }">
    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
  </el-select>
</template>

<script setup>
import api from '@/api/index'

defineOptions({
  name: 'SelectSearch',
  autoImport:true
})

const props = defineProps({
  info: {
    type: Object,
    default: () => {
      return {
        interfaceName: 'acctOrgList',
        label: 'orgName',
        value: 'orgCode',
        code: null,
        fileName: 'account',
        params: {},
        keyword: 'codeOrName',
        placeholder: '请输入编码和名称',
        needPage: true
      }
    }
  },
  value: {
    type: String,
    default: ''
  }
})

const options = ref([])

const loading = ref(false)

const timer = ref(null)

const emit = defineEmits(['on-selectListData', 'update:value'])
// 搜索发送请求
const remoteMethod = (query) => {
  if (query) {
    clearTimeout(timer.value)
    loading.value = true
    timer.value = setTimeout(() => {
      loading.value = false
      getList(query)
    }, 500)
  } else {
    options.value = []
  }
}
// 获取组织机构，即公司列表
const getList = (val) => {
  const {interfaceName, label, value, fileName, params, keyword, code, needPage} = props.info
  let parms = {
    ...params
  }
  if (needPage != false) {
    parms.pageSize = 20
    parms.pageNum = 1
  }
  console.log(fileName, 'fileName', interfaceName)
  parms[keyword] = val
  api[fileName][interfaceName](parms).then(res => {
    const {list} = res
    list.forEach(item => {
      let codeName = code ? `(${item[code]})` : `(${item[value]})`
      item['label'] = item[label] + codeName
      item['value'] = item[value]
    });
    options.value = list
    emit('on-selectListData', list)

  })

}

watchEffect(() => {

  setTimeout(() => {
    console.log('new', props.value, 'old', props)
    getList(props.value)
  }, 500)

})

</script>

<style lang="scss" scoped>
// scss
</style>
